import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from '../utils/storage'
Vue.use(VueRouter)

//! ==================修复vue重复点击同一路有报错，报错信息如下=============================
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
const originalReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace(location) {
  return originalReplace.call(this, location).catch(err => err)
}


let router = new VueRouter({
  routes: [
    {
      path: '/',
      component: () => import('@/pages/Layout'),
      children: [
        {
          path: '/',
          component: () => import('@/pages/Index')
        },
        {
          path: '/add',
          component: () => import('@/pages/Add')
        },
        {
          path: '/cate',
          component: () => import('@/pages/Cate')
        },
        {
          path: '/user',
          component: () => import('@/pages/User'),
        },
      ]
    },
    {
      path: '/user/sc',
      component: () => import('@/pages/User/Sc'),
      meta: { needLogin: true }
    },
    {
      path: '/user/zan',
      component: () => import('@/pages/User/Zan'),
      meta: { needLogin: true }
    },
    {
      path: '/user/article',
      component: () => import('@/pages/User/Article'),
      meta: { needLogin: true }
    },
    {
      path: '/user/edit',
      component: () => import('@/pages/User/Edit')
    },
    {
      path: '/list',
      component: () => import('@/pages/List')
    },
    {
      path: '/show',
      component: () => import('@/pages/Show')
    },
    {
      path: '/login',
      component: () => import('@/pages/Login')
    },
    {
      path: '/reg',
      component: () => import('@/pages/Reg')
    },

  ]
})


// 全局前置导航守卫
const blackPath = ['/user/sc', '/user/zan','/user/article','/user/edit']
router.beforeEach((to, from, next) => {
  // 判断是否登录，登录过，直接跳转
  if (getToken('token')) {
    next()
  } else {
    // 判断跳转的页面是否需要登录
    if (!blackPath.includes(to.path)) {
      next()
    } else {
      // 属于非法访问，跳转到登录
      next('/login')
    }
  }
})

export default router